import React, { useState, useEffect } from 'react';
import { ShoppingCart, BookOpen, CreditCard, CheckCircle, Lock, Trash2, X, User } from 'lucide-react';

// --- Mock Data ---
const COURSES = [
  {
    id: 1,
    title: "Introduction to Python",
    description: "Learn the basics of Python programming from scratch.",
    price: 0,
    thumbnail: "bg-emerald-100",
    icon: "🐍",
    category: "Development"
  },
  {
    id: 2,
    title: "Advanced React Patterns",
    description: "Master hooks, context, and performance optimization.",
    price: 49.99,
    thumbnail: "bg-blue-100",
    icon: "⚛️",
    category: "Development"
  },
  {
    id: 3,
    title: "Digital Marketing 101",
    description: "Understanding SEO and social media strategies.",
    price: 0,
    thumbnail: "bg-purple-100",
    icon: "📢",
    category: "Marketing"
  },
  {
    id: 4,
    title: "UX/UI Design Masterclass",
    description: "From wireframes to high-fidelity prototypes.",
    price: 89.00,
    thumbnail: "bg-orange-100",
    icon: "🎨",
    category: "Design"
  }
];

// --- Components ---

const Button = ({ children, onClick, variant = 'primary', className = '', disabled = false }) => {
  const baseStyle = "px-4 py-2 rounded-lg font-medium transition-all duration-200 flex items-center justify-center gap-2";
  const variants = {
    primary: "bg-blue-600 text-white hover:bg-blue-700 disabled:bg-blue-300",
    secondary: "bg-gray-100 text-gray-700 hover:bg-gray-200",
    outline: "border-2 border-gray-200 text-gray-700 hover:border-gray-300",
    success: "bg-emerald-600 text-white hover:bg-emerald-700",
    danger: "text-red-500 hover:bg-red-50 hover:text-red-600"
  };

  return (
    <button 
      onClick={onClick} 
      disabled={disabled}
      className={`${baseStyle} ${variants[variant]} ${className}`}
    >
      {children}
    </button>
  );
};

export default function CourseRegistrationApp() {
  // State
  const [view, setView] = useState('catalog'); // catalog, cart, login, checkout, success, dashboard
  const [cart, setCart] = useState([]);
  const [user, setUser] = useState(null); // null = Guest, object = Logged In
  const [enrolledCourses, setEnrolledCourses] = useState([]);
  const [isProcessing, setIsProcessing] = useState(false);

  // Derived State
  const cartTotal = cart.reduce((sum, item) => sum + item.price, 0);
  const isCartFree = cartTotal === 0;

  // Actions
  const addToCart = (course) => {
    if (!cart.find(c => c.id === course.id) && !enrolledCourses.find(c => c.id === course.id)) {
      setCart([...cart, course]);
    }
  };

  const removeFromCart = (courseId) => {
    setCart(cart.filter(c => c.id !== courseId));
  };

  const handleLogin = (e) => {
    e.preventDefault();
    setUser({ name: "Alex Student", email: "alex@example.com" });
    // Redirect logic: If they were trying to checkout, go back to checkout
    setView('checkout');
  };

  const processOrder = () => {
    setIsProcessing(true);
    
    // Simulate API call
    setTimeout(() => {
      setEnrolledCourses([...enrolledCourses, ...cart]);
      setCart([]);
      setIsProcessing(false);
      setView('success');
    }, 2000);
  };

  // --- Views ---

  const CatalogView = () => (
    <div className="space-y-6">
      <div className="text-center py-8">
        <h2 className="text-3xl font-bold text-gray-900">Explore Courses</h2>
        <p className="text-gray-500 mt-2">Start your learning journey today. Free and Premium courses available.</p>
      </div>
      
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-4 gap-6">
        {COURSES.map(course => {
          const inCart = cart.find(c => c.id === course.id);
          const isEnrolled = enrolledCourses.find(c => c.id === course.id);

          return (
            <div key={course.id} className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-md transition-shadow">
              <div className={`h-32 ${course.thumbnail} flex items-center justify-center text-4xl`}>
                {course.icon}
              </div>
              <div className="p-5">
                <div className="flex justify-between items-start mb-2">
                  <span className="text-xs font-semibold tracking-wider text-gray-500 uppercase">{course.category}</span>
                  <span className={`px-2 py-1 rounded text-xs font-bold ${course.price === 0 ? 'bg-emerald-100 text-emerald-700' : 'bg-blue-100 text-blue-700'}`}>
                    {course.price === 0 ? 'FREE' : `$${course.price}`}
                  </span>
                </div>
                <h3 className="font-bold text-lg mb-1">{course.title}</h3>
                <p className="text-sm text-gray-500 mb-4 h-10 line-clamp-2">{course.description}</p>
                
                {isEnrolled ? (
                  <Button variant="secondary" className="w-full cursor-default">
                    <CheckCircle size={16} /> Enrolled
                  </Button>
                ) : inCart ? (
                  <Button variant="outline" className="w-full" onClick={() => setView('cart')}>
                    View in Cart
                  </Button>
                ) : (
                  <Button variant="primary" className="w-full" onClick={() => addToCart(course)}>
                    Add to Cart
                  </Button>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );

  const CartView = () => (
    <div className="max-w-2xl mx-auto">
      <h2 className="text-2xl font-bold mb-6 flex items-center gap-2">
        <ShoppingCart /> Your Cart
      </h2>
      
      {cart.length === 0 ? (
        <div className="text-center py-12 bg-white rounded-xl border border-dashed border-gray-300">
          <p className="text-gray-500 mb-4">Your cart is empty.</p>
          <Button onClick={() => setView('catalog')}>Browse Courses</Button>
        </div>
      ) : (
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          <div className="divide-y divide-gray-100">
            {cart.map(item => (
              <div key={item.id} className="p-4 flex items-center justify-between">
                <div className="flex items-center gap-4">
                  <div className={`w-12 h-12 rounded-lg ${item.thumbnail} flex items-center justify-center text-xl`}>
                    {item.icon}
                  </div>
                  <div>
                    <h4 className="font-medium">{item.title}</h4>
                    <p className="text-sm text-gray-500">{item.price === 0 ? 'Free Course' : 'Standard License'}</p>
                  </div>
                </div>
                <div className="flex items-center gap-6">
                  <span className="font-bold text-gray-900">{item.price === 0 ? 'FREE' : `$${item.price.toFixed(2)}`}</span>
                  <button onClick={() => removeFromCart(item.id)} className="text-gray-400 hover:text-red-500">
                    <Trash2 size={18} />
                  </button>
                </div>
              </div>
            ))}
          </div>
          <div className="bg-gray-50 p-6">
            <div className="flex justify-between items-center mb-6 text-lg">
              <span className="font-medium">Total:</span>
              <span className="font-bold text-2xl">{cartTotal === 0 ? 'FREE' : `$${cartTotal.toFixed(2)}`}</span>
            </div>
            <Button 
              className="w-full py-3 text-lg" 
              onClick={() => user ? setView('checkout') : setView('login')}
            >
              Checkout <CheckCircle size={20} />
            </Button>
          </div>
        </div>
      )}
    </div>
  );

  const LoginGate = () => (
    <div className="max-w-md mx-auto mt-10">
      <div className="bg-white p-8 rounded-xl shadow-lg border border-gray-100">
        <div className="text-center mb-6">
          <div className="bg-blue-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4 text-blue-600">
            <User size={32} />
          </div>
          <h2 className="text-2xl font-bold">Student Login</h2>
          <p className="text-gray-500">Please identify yourself to register.</p>
        </div>
        
        <form onSubmit={handleLogin} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Email Address</label>
            <input 
              type="email" 
              defaultValue="student@demo.com"
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
            <input 
              type="password" 
              defaultValue="password"
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
            />
          </div>
          <Button className="w-full">Sign In to Continue</Button>
        </form>
        <div className="mt-4 text-center">
          <button onClick={() => setView('catalog')} className="text-sm text-gray-500 hover:underline">Cancel and browse catalog</button>
        </div>
      </div>
    </div>
  );

  const CheckoutView = () => (
    <div className="max-w-4xl mx-auto grid grid-cols-1 md:grid-cols-2 gap-8">
      {/* Order Summary */}
      <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200 h-fit">
        <h3 className="font-bold text-lg mb-4">Order Summary</h3>
        <div className="space-y-3 mb-6">
          {cart.map(item => (
            <div key={item.id} className="flex justify-between text-sm">
              <span className="text-gray-600">{item.title}</span>
              <span className="font-medium">{item.price === 0 ? 'FREE' : `$${item.price.toFixed(2)}`}</span>
            </div>
          ))}
        </div>
        <div className="border-t pt-4 flex justify-between items-center">
          <span className="font-bold text-gray-900">Total Due</span>
          <span className="font-bold text-2xl text-blue-600">{cartTotal === 0 ? '$0.00' : `$${cartTotal.toFixed(2)}`}</span>
        </div>
      </div>

      {/* The Logic Fork UI */}
      <div className="space-y-6">
        {/* User Identity */}
        <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200">
          <div className="flex items-center gap-3 mb-2">
            <div className="bg-green-100 p-2 rounded-full text-green-700"><CheckCircle size={16}/></div>
            <h3 className="font-bold">Account Verified</h3>
          </div>
          <p className="text-gray-600 text-sm">Registering as <span className="font-semibold text-gray-900">{user.name}</span></p>
          <p className="text-gray-500 text-sm">{user.email}</p>
        </div>

        {/* Dynamic Payment Section */}
        <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200 relative overflow-hidden">
          {isProcessing && (
            <div className="absolute inset-0 bg-white/80 z-10 flex items-center justify-center flex-col">
              <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mb-2"></div>
              <p className="font-semibold text-blue-900">Processing Registration...</p>
            </div>
          )}

          <h3 className="font-bold text-lg mb-4 flex items-center gap-2">
            {isCartFree ? <CheckCircle className="text-emerald-600" /> : <CreditCard className="text-blue-600" />}
            {isCartFree ? "Finalize Enrollment" : "Payment Details"}
          </h3>

          {isCartFree ? (
            // --- SCENARIO B: FREE PATH ---
            <div className="bg-emerald-50 border border-emerald-100 rounded-lg p-4 mb-4">
              <p className="text-emerald-800 font-medium mb-1">No Payment Required</p>
              <p className="text-emerald-600 text-sm">Because your order total is $0.00, you can skip the payment processor and enroll immediately.</p>
            </div>
          ) : (
            // --- SCENARIO A: PAID PATH ---
            <div className="space-y-4 mb-6">
              <div className="bg-blue-50 border border-blue-100 rounded-lg p-3 text-sm text-blue-800 mb-2">
                Secure SSL Encrypted Transaction
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wide mb-1">Card Number</label>
                <div className="relative">
                  <CreditCard className="absolute left-3 top-2.5 text-gray-400" size={18} />
                  <input type="text" placeholder="0000 0000 0000 0000" className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wide mb-1">Expiry</label>
                  <input type="text" placeholder="MM/YY" className="w-full px-4 py-2 border border-gray-300 rounded-lg" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-gray-500 uppercase tracking-wide mb-1">CVC</label>
                  <input type="text" placeholder="123" className="w-full px-4 py-2 border border-gray-300 rounded-lg" />
                </div>
              </div>
            </div>
          )}

          <Button 
            onClick={processOrder} 
            variant={isCartFree ? "success" : "primary"}
            className="w-full py-3 text-lg shadow-lg"
          >
            {isCartFree ? "Complete Free Enrollment" : `Pay $${cartTotal.toFixed(2)}`}
          </Button>
        </div>
      </div>
    </div>
  );

  const SuccessView = () => (
    <div className="max-w-md mx-auto text-center py-12">
      <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6 text-green-600 animate-bounce">
        <CheckCircle size={40} />
      </div>
      <h2 className="text-3xl font-bold text-gray-900 mb-2">You're In!</h2>
      <p className="text-gray-500 mb-8">
        Registration successful. A receipt has been sent to {user.email}.
      </p>
      <div className="space-y-3">
        <Button onClick={() => setView('dashboard')} className="w-full">
          Go to My Learning
        </Button>
        <Button variant="outline" onClick={() => setView('catalog')} className="w-full">
          Browse More Courses
        </Button>
      </div>
    </div>
  );

  const DashboardView = () => (
    <div>
       <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">My Learning Dashboard</h2>
        <Button variant="outline" onClick={() => setView('catalog')}>Browse Catalog</Button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {enrolledCourses.map(course => (
          <div key={course.id} className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
             <div className={`h-24 ${course.thumbnail} flex items-center justify-center text-3xl`}>
                {course.icon}
              </div>
              <div className="p-5">
                <h3 className="font-bold mb-2">{course.title}</h3>
                <div className="w-full bg-gray-100 rounded-full h-2 mb-4">
                  <div className="bg-blue-600 h-2 rounded-full" style={{ width: '0%' }}></div>
                </div>
                <div className="flex justify-between items-center text-sm text-gray-500 mb-4">
                  <span>0% Complete</span>
                </div>
                <Button className="w-full" variant="primary">Start Learning</Button>
              </div>
          </div>
        ))}
      </div>
    </div>
  );

  // --- Main Render ---

  return (
    <div className="min-h-screen bg-gray-50 font-sans text-gray-900">
      {/* Header */}
      <header className="bg-white border-b border-gray-200 sticky top-0 z-50">
        <div className="max-w-6xl mx-auto px-4 h-16 flex items-center justify-between">
          <div className="flex items-center gap-2 cursor-pointer" onClick={() => setView('catalog')}>
            <div className="bg-blue-600 text-white p-1.5 rounded-lg">
              <BookOpen size={20} />
            </div>
            <span className="font-bold text-xl tracking-tight">EduPath</span>
          </div>

          <nav className="flex items-center gap-6">
            <button 
              onClick={() => setView('catalog')}
              className={`text-sm font-medium ${view === 'catalog' ? 'text-blue-600' : 'text-gray-500 hover:text-gray-900'}`}
            >
              Catalog
            </button>
            {user && (
              <button 
                onClick={() => setView('dashboard')}
                className={`text-sm font-medium ${view === 'dashboard' ? 'text-blue-600' : 'text-gray-500 hover:text-gray-900'}`}
              >
                My Learning
              </button>
            )}
          </nav>

          <div className="flex items-center gap-4">
            {user ? (
               <div className="hidden md:flex items-center gap-2 text-sm text-gray-600 bg-gray-100 px-3 py-1.5 rounded-full">
                  <User size={14} />
                  {user.name}
               </div>
            ) : (
              <button onClick={() => setView('login')} className="text-sm font-medium text-gray-600 hover:text-blue-600">
                Log In
              </button>
            )}

            <button 
              className="relative p-2 text-gray-600 hover:bg-gray-100 rounded-full transition-colors"
              onClick={() => setView('cart')}
            >
              <ShoppingCart size={24} />
              {cart.length > 0 && (
                <span className="absolute top-0 right-0 bg-red-500 text-white text-[10px] font-bold w-5 h-5 flex items-center justify-center rounded-full border-2 border-white">
                  {cart.length}
                </span>
              )}
            </button>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-6xl mx-auto px-4 py-8">
        {view === 'catalog' && <CatalogView />}
        {view === 'cart' && <CartView />}
        {view === 'login' && <LoginGate />}
        {view === 'checkout' && <CheckoutView />}
        {view === 'success' && <SuccessView />}
        {view === 'dashboard' && <DashboardView />}
      </main>
    </div>
  );
}